package xin.shaozeming.base.common.quartz;

import lombok.extern.log4j.Log4j2;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;

import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.annotation.Resource;

/**
 * @author: 邵泽铭
 * @date: 2019/10/17
 * @description:
 **/
@Log4j2
@Configuration
public class ApplicationStartQuartzJobListener  implements ApplicationListener<ContextRefreshedEvent> {
    @Resource
    private DynamicQuartzScheduler dynamicQuartzScheduler;

    /**
     * 初始启动quartz
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            dynamicQuartzScheduler.startAllJob();
            log.info("任务已经启动...");
        } catch (SchedulerException e) {
            log.error("定时器启动失败,定时器已停止 {}",e.getMessage() );
        }
    }

    /**
     * 初始注入scheduler
     * @return
     * @throws SchedulerException
     */
    @Bean
    public Scheduler scheduler() throws SchedulerException{
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
        return schedulerFactoryBean.getScheduler();
    }

}
